from django.core.paginator import PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

from django.views.generic import View
# Create your views here.
from pure_pagination import Paginator

from educationOnline.settings import MEDIA_URL
from organization.forms import UserAskForm
from .models import CourseOrg, CityDict


class OrgView(View):
    """
    课程机构列表功能
    """

    def get(self, request):
        # 课程机构
        all_orgs = CourseOrg.objects.all()
        # 城市
        all_citys = CityDict.objects.all()


        # 机构搜索功能
        search_keyword = request.GET.get('keyword', "")
        if search_keyword:
            # 名字中包含这个地名，或者是在地址中包含这个名字的都给查询出来
            all_orgs = all_orgs.filter(Q(name__contains=search_keyword) | Q(desc__contains=search_keyword))

        # 城市筛选
        city_id = request.GET.get('city', '')
        if city_id:
            all_orgs = all_orgs.filter(city_id=int(city_id))
        # 类别筛选
        category = request.GET.get('ct', '')
        if category:
            all_orgs = all_orgs.filter(category=category)
        # 人们课程机构排名
        hot_orgs = all_orgs.order_by('-click_nums')[:3]

        # 学习人数和课程筛选
        sort = request.GET.get('sort', "")
        if sort:
            if sort == "students":
                all_orgs = all_orgs.order_by("-students")
            elif sort== "courses":
                all_orgs = all_orgs.order_by("-course_nums")
            else:
                pass

        # 有多少家机构
        org_nums = all_orgs.count()
        # 对课程机构进行分页
        # 尝试获取前台get请求传递过来的page参数
        # 如果是不合法的配置参数默认返回第一页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 这里指从allorg中取五个出来，每页显示5个
        p = Paginator(all_orgs, 2, request=request)
        orgs = p.page(page)
        # orgs.number 是当前点击的页数，首次进入是第一页
        return render(request, 'org-list.html', {
            "all_orgs": orgs,
            "all_citys": all_citys,
            "org_nums": org_nums,
            "MEDIA_URL": MEDIA_URL,
            "city_id":city_id,
            "sort":sort,
            'hot_orgs':hot_orgs,
            "category": category,
        })

class AddUserAskView(View):
    '''
    用户咨询
    '''
    def post(self,request):
        userask_form = UserAskForm(request.POST)
        if userask_form.is_valid():
            user_ask = userask_form.save(commit=True)
            print(user_ask)
            # 如果保存成功,返回json字符串,后面content type是告诉浏览器返回的数据类型
            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse("{'status':'fail','msg':{0}}".format(userask_form.errors), content_type='application/json')
